package com.xuecheng.base.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器，可以设置po类的自动填充规则
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert...]");
        log.info(metaObject.toString());
        //fillStrategy不会检查属性是否存在，如果属性不存在，则直接跳过，则不自动填充，也不抛异常
        fillStrategy(metaObject,"createTime", LocalDateTime.now());
        fillStrategy(metaObject,"createDate", LocalDateTime.now());
        fillStrategy(metaObject,"updateTime", LocalDateTime.now());
        fillStrategy(metaObject,"updateDate", LocalDateTime.now());
        //也可以手动检查这个类是否存在这个属性
        if(metaObject.hasSetter("changeDate")){
            strictInsertFill(metaObject,"changeDate",LocalDateTime.class,LocalDateTime.now());
        }
        if(metaObject.hasSetter("changeTime")){
            strictInsertFill(metaObject,"changeTime",LocalDateTime.class,LocalDateTime.now());
        }
    }

    /**
     * 更新时自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update...]");
        log.info(metaObject.toString());
        fillStrategy(metaObject,"updateDate",LocalDateTime.now());
        fillStrategy(metaObject,"updateTime",LocalDateTime.now());
        fillStrategy(metaObject,"changeTime",LocalDateTime.now());
        fillStrategy(metaObject,"changeDate",LocalDateTime.now());
    }
}
